#!/bin/sh
### BEGIN INIT INFO
# Provides:          change_password
# Required-Start:    $local_fs
# Required-Stop:
# Default-Start:     3
# Default-Stop:
# Short-Description: Change pi's password via /boot/octopi-password.txt
# Description:
### END INIT INFO

. /lib/lsb/init-functions

do_start () {
  text_file="/boot/octopi-password.txt"
  if [ ! -f "$text_file" ]
  then
    exit 0
  fi

  new_password=`head -n1 "$text_file" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' | tr -d '\n'` 
  if [ ! -n "$new_password" ]
  then
    log_failure_msg "No new password provided, refusing to change to empty password"
    exit 1
  fi

  (echo "pi:$new_password" | chpasswd && rm "$text_file" && log_success_msg "Password for user pi changed and change file deleted") || log_failure_msg "Could not change password"
}

case "$1" in
  start|"")
        do_start
        ;;
  restart|reload|force-reload)
        echo "Error: argument '$1' not supported" >&2
        exit 3
        ;;
  stop)
        # No-op
        ;;
  *)
        echo "Usage: change_password [start|stop]" >&2
        exit 3
        ;;
esac
